package com.taotao.rest.service.impl;

import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.rest.service.TbContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TbContentServiceImpl implements TbContentService {

    @Autowired
    private TbContentMapper tbContentMapper;

    @Autowired
    //private StringRedisTemplate redisTemplate;
    private RedisTemplate redisTemplate;

    @Value("${taotao.redis.keys.hash_prefix}")
    private String hashKeyPrefix;

    @Value("${taotao.redis.keys.content_prefix}")
    private String contentKeyPrefix;

    /**
     * 根据类别id（categoryId）查询前端页面轮播图
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<TbContent> getAllContent(Long categoryId) {

        //添加缓存:如果访问缓存异常,应该正常查询数据库,而不是直接报错
        //缓存逻辑:请求进来.先去redis缓存中查询,如果有,直接返回.
        //否则,直接查询数据库.将结果放入redis缓存中,然后返回.
        String key = contentKeyPrefix + categoryId;
        Object obj = redisTemplate.opsForHash().get(hashKeyPrefix, key);
        if (obj == null) {
            TbContentExample condition = new TbContentExample();
            condition.createCriteria().andCategoryIdEqualTo(categoryId);
            List<TbContent> tbContentList = tbContentMapper.selectByExampleWithBLOBs(condition);
            redisTemplate.opsForHash().put(hashKeyPrefix, key, tbContentList);
            obj = tbContentList;
        }
        List<TbContent> tbContentList = (List<TbContent>) obj;
        return tbContentList;
    }
}
